package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public ResultInfo login(String username, String password) {
        Employee employee = employeeMapper.findByUserName(username);
        if(employee == null){
            return ResultInfo.error("用户不存在");
        }
        /*如果employee不为空，给前端传入的密码使用md5加密*/
        String passwordWithMd5 = SecureUtil.md5(password);
        System.out.println(passwordWithMd5);
        if(!StringUtils.equals(passwordWithMd5,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }
        if(employee.getStatus() == Employee.STATUS_DISABLE){
            return ResultInfo.error("用户已禁用");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) {
        /*
        * 前端参数并不完整，所以要补齐参数
        * */
//        //todo 雪花算法学习   设置唯一主键id
//        employee.setId(IdUtil.getSnowflake(1,1).nextId());
//        //设置默认密码，对密码进行加密并赋值给employee对象
        //设置默认密码
        employee.setPassword(SecureUtil.md5("123"));

        //设置默认状态
        employee.setStatus(Employee.STATUS_ENABLE);
//        /*//员工创建日期
//        employee.setCreateTime(new Date());
//        //员工更新日期
//        employee.setUpdateTime(new Date());
//        //todo  先写死，后面重新编写逻辑
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);*/

        //存入数据库
        employeeMapper.insert(employee);
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
        /*//员工创建日期
        employee.setCreateTime(new Date());
        //员工更新日期
        employee.setUpdateTime(new Date());
        //todo  先写死，后面重新编写逻辑
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/
        employeeMapper.updateById(employee);
    }
}
